using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Mistral
{
	public interface ITrigger
	{
		bool Check( );
	}

	public class TriggerManager
	{
		private static Timer _timer;
		private static readonly List<ITrigger> _triggers = new List<ITrigger>( );
		private static readonly Dictionary<Type,EventHandler> _handlers = new Dictionary<Type, EventHandler>( );

		public static void StartTriggers( object target )
		{
			if( target != null )
			{
				object[] triggers = App.Instance.ServiceManager.GetServices( target, typeof(ITrigger) );
				foreach ( ITrigger trigger in triggers )
				{
					StartTrigger( trigger, 500 );
				}				
			}
		}

		public static void StopTriggers( object target )
		{
			if( target != null )
			{
				object[] triggers = App.Instance.ServiceManager.GetServices( target, typeof(ITrigger) );
				foreach ( ITrigger trigger in triggers )
				{
					StopTrigger( trigger );
				}				
			}
		}
		
		public static void StartTrigger( ITrigger trigger, int ms )
		{
			if( _timer == null )
			{
				_timer = new Timer();
				_timer.Interval = 500;
				_timer.Tick += Tick;
				_timer.Start();				
			}
			lock( _triggers )
			{
				_triggers.Add( trigger );
			}
		}

		public static void StopTrigger( ITrigger trigger )
		{
			lock( _triggers )
			{
				_triggers.Remove( trigger );
			}
		}

		public static void RegisterTriggerAction( Type triggerType, EventHandler triggerEventHandler )
		{
			_handlers[triggerType] = triggerEventHandler;
		}

		private static void Tick( object sender, EventArgs e )
		{
			lock( _triggers )
			{
				foreach ( ITrigger trigger in _triggers )
				{
					if( trigger.Check() )
					{
						_handlers[trigger.GetType()]( trigger, EventArgs.Empty );
					}
				}
			}
		}

	}
}
